#include "SerialSelectDialog.h"
#include "ui_SerialSelectDialog.h"


SerialSelectDialog::SerialSelectDialog(QWidget* parent)
    : QDialog(parent)
    , selectSerialPort("")
    , ui(new Ui::SerialSelectDialog)
{
    ui->setupUi(this);

    // 设置窗口标题
    setWindowTitle("Serial Port Selector");

    // 创建模型
    model = new QStringListModel(this);

    // 设置ListView的模型
    ui->listView->setModel(model);
}

SerialSelectDialog::~SerialSelectDialog()
{
    delete ui;
}

void SerialSelectDialog::on_pushButton_clicked()
{
    // 清空当前列表
    model->setStringList(QStringList());

    // 获取当前可用的串口信息
    QList<QSerialPortInfo> availablePorts = QSerialPortInfo::availablePorts();
    QStringList portNames;
    for (const QSerialPortInfo& port : availablePorts) {
        // portNames << port.portName() + " - " + port.description();
        portNames << port.portName();
    }

    // 更新模型
    model->setStringList(portNames);
}


void SerialSelectDialog::on_buttonBox_accepted()
{
    auto current = ui->listView->currentIndex();
    selectSerialPort = model->data(current, Qt::DisplayRole).toString();
}


void SerialSelectDialog::on_buttonBox_rejected()
{
    selectSerialPort = "";
}

std::optional<QString> SerialSelectDialog::getSelectSerialPort()
{
    if (selectSerialPort == "") {
        return std::nullopt;
    }
    else {
        return std::optional(selectSerialPort);
    }
}
